package cn.cheqi.recovery.background.controller;


import cn.cheqi.recovery.background.dto.DataGridView;
import cn.cheqi.recovery.background.dto.ResultDTO;
import cn.cheqi.recovery.background.entity.Building;
import cn.cheqi.recovery.background.entity.Community;
import cn.cheqi.recovery.background.entity.Owner;
import cn.cheqi.recovery.background.entity.User;
import cn.cheqi.recovery.background.mapper.CommunityMapper;
import cn.cheqi.recovery.background.service.CommunityService;
import cn.cheqi.recovery.background.utils.SysFileUtils;
import cn.cheqi.recovery.background.vo.CommunityVO;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  小区前端控制器
 * </p>
 *
 * @author Robin
 * @since 2020-02-23
 */
@RestController
@RequestMapping("/system/community")
public class CommunityController {

    @Autowired
    private CommunityService communityService;

    @Autowired
    private CommunityMapper communityMapper;

    /**
     * 加载所有小区
     * @param communityVO
     * @return
     */
    @RequestMapping("/loadAllCommunities")
    public DataGridView loadAllCommunities(CommunityVO communityVO){

        IPage<Community> page = new Page<>(communityVO.getPage(),communityVO.getLimit());
        QueryWrapper<Community> wrapper = new QueryWrapper<>();
        //商家名称
        String communityName = communityVO.getCommunityName();
        //商家联系方式
        String communityPhone = communityVO.getCommunityPhone();
        //商家详细地址
        String detailedAddress = communityVO.getDetailedAddress();
        //去掉三个查询条件里面的空格
        if (!StringUtils.isBlank(communityName)){
            String sName = communityName.replace(" ", "");
            wrapper.like(!StringUtils.isBlank(sName),"community_name",sName);
        }

        if (!StringUtils.isBlank(communityPhone)){
            String sPhone = communityPhone.replace(" ", "");
            wrapper.like(!StringUtils.isBlank(sPhone),"community_phone",sPhone);
        }

        if (!StringUtils.isBlank(detailedAddress)){
            String sAddress = detailedAddress.replace(" ", "");
            wrapper.like(!StringUtils.isBlank(sAddress),"detailed_address",sAddress);
        }
        wrapper.orderByDesc("community_id");
        communityService.page(page,wrapper);
        return new DataGridView(page.getTotal(),page.getRecords());
    }

    /**
     * 添加小区
     * @param communityVO
     * @return
     */
    @PostMapping("/addCommunity")
    @Transactional
    public ResultDTO addCommunity(CommunityVO communityVO){
        try {
            //判断图片后缀是否包含_temp
            if (communityVO.getCommunityPic() != null && communityVO.getCommunityPic().contains("_temp")){
                String afterUrl = SysFileUtils.moveAllTemp(communityVO.getCommunityPic());
                communityVO.setCommunityPic(afterUrl);
            }
            communityService.save(communityVO);
            return new ResultDTO(200,"添加成功");
        } catch (Exception e){
            e.printStackTrace();
            return new ResultDTO(-1,"添加失败");
        }
    }

    /**
     * 通过小区ID删除小区信息以及图片
     * @param communityVO
     * @return
     */
    @RequestMapping("/deleteCommunityById")
    @Transactional
    public ResultDTO deleteCommunityById(CommunityVO communityVO){
        try{
            //获取到商家的图片路径
            String communityPics = communityService.getById(communityVO.getCommunityId()).getCommunityPic();
            if (communityPics != null){
                SysFileUtils.deleteCommunityPics(communityPics);
            }
            communityService.removeById(communityVO.getCommunityId());
            return new ResultDTO(200,"删除成功");
        } catch (Exception e){
            e.printStackTrace();
            return new ResultDTO(-1,"删除失败");
        }
    }

    /**
     * 通过ID修改小区信息
     * @param communityVO
     * @return
     */
    @PostMapping("/editCommunity")
    @Transactional
    public ResultDTO editCommunityById(CommunityVO communityVO){
        try {
            System.out.println(communityVO);
            communityService.updateById(communityVO);
            return new ResultDTO(200,"修改成功");
        } catch (Exception e){
            e.printStackTrace();
            return new ResultDTO(-1,"修改失败");
        }
    }

    /**
     * 商家的多图片上传
     * @param multipartFile
     * @return
     */
    @RequestMapping("/file/uploadCommunityPic")
    @Transactional
    public Map<String,Object> uploadFirmImg(@RequestParam("file") MultipartFile multipartFile){
            Map<String,Object> map = new HashMap<String, Object>();
            //遍历每个商家图片
            if (!(multipartFile.getSize() == 0)){
                //1.得到文件的老名字
                //System.out.println(multipartFile.getOriginalFilename());
                String oldFileName = multipartFile.getOriginalFilename();
                //2.根据文件名生成新的文件名
                String newName = SysFileUtils.createNewFileName(oldFileName);
                //3.得到当前日期的字符串
                String dirName = DateUtil.format(new Date(),"yyyy-MM-dd");
                //构造商家存储的文件夹
                String communitySave = SysFileUtils.Community_Save_Folder + dirName;
                //4.构造商家文件夹
                File dirFile = new File(SysFileUtils.UPLOAD_PATH,communitySave);
                //5.判断当前文件夹是否存在
                if (!dirFile.exists()){
                    //如果不存在则创建这个文件夹
                    dirFile.mkdirs();
                }
                //6.构造文件对象
                File file = new File(dirFile, newName+"_temp");
                //7.把mf里面的图片信息写入file
                try {
                    multipartFile.transferTo(file);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //8.返回图片的相对路径
                map.put("path",communitySave+"/"+newName+"_temp");
            }
        return map;
    }

    /**
     * 商家文件下载
     * @param path
     * @return
     */
    @RequestMapping("/file/showPicByPath")
    public ResponseEntity<Object> showPicByPath(String path){
        return SysFileUtils.createResponseEntity(path);
    }

    /**
     * 通过小区ID查出该小区下所有未入驻的业主信息
     * @param communityVO
     * @return
     */
    @PostMapping("/findAllOwnersByCommunityId")
    public DataGridView findAllOwnersByCommunityId(CommunityVO communityVO){
        //分页条件
        Page<Community> page = new Page<>();
        if (communityVO.getPage() != null && communityVO.getLimit() != null){
            page.setPages(communityVO.getPage());
            page.setSize(communityVO.getLimit());
        }
        List<Owner> owners = communityMapper.findAllOwnersByCommunityId(communityVO.getCommunityId(),page);
        return new DataGridView(page.getTotal(),owners);
    }

    /**
     * 通过小区ID查出该小区下所有已入驻的业主信息
     * @param communityVO
     * @return
     */
    @PostMapping("/findAllUsersByCommunityId")
    public DataGridView findAllUsersByCommunityId(CommunityVO communityVO){
        //分页条件
        Page<Community> page = new Page<>();
        if (communityVO.getPage() != null && communityVO.getLimit() != null){
            page.setPages(communityVO.getPage());
            page.setSize(communityVO.getLimit());
        }
        List<User> users = communityMapper.findAllUsersByCommunityId(communityVO.getCommunityId(),page);
        return new DataGridView(page.getTotal(),users);
    }

    /**
     * 通过小区ID查出该小区下所有楼栋信息
     * @param communityVO
     * @return
     */
    @PostMapping("/findAllBuildingsByCommunityId")
    public DataGridView findAllBuildingsByCommunityId(CommunityVO communityVO){
        //分页条件
        Page<Community> page = new Page<>();
        if (communityVO.getPage() != null && communityVO.getLimit() != null){
            page.setCurrent(communityVO.getPage());
            page.setSize(communityVO.getLimit());
        }
        List<Building> buildings = communityMapper.findAllBuildingsByCommunityId(communityVO.getCommunityId(),page);
        Map<Object,Object> map = new HashMap<>();
        map.put("list",buildings);
        map.put("curr",page.getCurrent());
        map.put("pages",page.getSize());
        map.put("count",page.getTotal());
        return new DataGridView(page.getTotal(),map);
    }
}

